﻿using Microsoft.Toolkit.Mvvm.ComponentModel;
using SimpleBoard.DependencyInjection;
using SimpleBoard.Project.Binding;
using SimpleBoard.Project.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleBoard.Designer.ViewModels
{
    [InjectAs(InjectionType.Singleton)]
    public class DataProtocolDesignerPageViewModel : ObservableRecipient
    {
        private ObservableCollection<DataUnit> dataUnits = new();
        public ObservableCollection<DataBinding> DataBindings { get; private set; } = new();

        private string? inputDataUnitName;
        private (string Name, DataUnitType Type)? selectedType;

        public IEnumerable<(string Name, DataUnitType Type)> DataUnitTypes => new List<(string Name, DataUnitType Type)>
        {
            new ("32位整型", DataUnitType.Int32),
            new ("32位浮点型", DataUnitType.Float32),
            new ("8位布尔型", DataUnitType.Bool),
            new ("字符串", DataUnitType.String),
        };

        public ObservableCollection<DataUnit> DataUnits
        {
            get => dataUnits;
            set { dataUnits = value; SetProperty(ref dataUnits, value); }
        }

        public string? InputDataUnitName
        {
            get => inputDataUnitName;
            set => SetProperty(ref inputDataUnitName, value);
        }

        public (string Name, DataUnitType Type)? SelectedType
        {
            get => selectedType;
            set => SetProperty(ref selectedType, value);
        }

        /// <summary>
        /// 添加数据协议单元
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        public void AddUnit()
        {
            if (string.IsNullOrEmpty(this.inputDataUnitName) || this.selectedType is null) return;

            var existsQuery = from unit in dataUnits
                              where unit.Name == inputDataUnitName
                              select unit;
            if (existsQuery.Any()) return;

            dataUnits.Add(new DataUnit
            {
                Name = inputDataUnitName,
                Type = selectedType.Value.Type,
            });
        }

        /// <summary>
        /// 移除指定名称的数据协议单元
        /// </summary>
        /// <param name="name"></param>
        public void RemoveUnit(string name)
        {
            var existsQuery = from unit in dataUnits
                              where unit.Name == name
                              select unit;
            if (!existsQuery.Any()) return;

            dataUnits.Remove(existsQuery.Single());
        }
    }
}
